
import { ref, computed } from 'vue'
import type { Comment } from '@/interface/commonData'

export function useCommentItem(props: {
  comment: Comment
  replies: Comment[]
  allComments: Comment[]
}, emit: (e: 'reply', content: string, parent: Comment) => void) {
  const showReply = ref(false)
  const expanded = ref(false)
  const replyContent = ref('')
  const replyTarget = ref<Comment | null>(null)

  const toggleReply = () => {
    showReply.value = !showReply.value
    replyTarget.value = props.comment
  }

  const toggleExpand = () => {
    expanded.value = !expanded.value
  }

  const submitReply = () => {
    if (!replyContent.value.trim() || !replyTarget.value) return
    emit('reply', replyContent.value, replyTarget.value)
    replyContent.value = ''
    showReply.value = false
    replyTarget.value = null
  }

  const prepareReply = (reply: Comment) => {
    showReply.value = true
    replyTarget.value = reply
  }

  const childReplies = computed(() => {
    const result: Comment[] = []
    const queue: (number | null)[] = [props.comment.id]

    while (queue.length > 0) {
      const currentId = queue.shift()
      const children = props.replies.filter(r => r.parentId === currentId)
      result.push(...children)
      queue.push(...children.map(c => c.id))
    }

    return result
  })

  const getReplyTarget = (parentId: number | null) => {
    return props.allComments.find(c => c.id === parentId)?.username ?? '未知用户'
  }

  const formatTime = (time: Date | null) => {
    return time ? new Date(time).toLocaleString() : '未知时间'
  }

  return {
    showReply,
    expanded,
    replyContent,
    toggleReply,
    toggleExpand,
    submitReply,
    prepareReply,
    childReplies,
    getReplyTarget,
    formatTime
  }
}